<template>
  <div>
    <div style="display: flex; justify-content: space-between">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="handleAdd" style="margin: 10px 0">
        添加
      </el-button>
      <!-- 搜索框 -->
      <el-input v-model="search" placeholder="搜索用户" style="width: 200px" />
    </div>

    <!-- 添加用户弹窗 -->
    <GenericDialogForm
      :dialogTitle="'添加用户'"
      :dialogWidth="'30%'"
      v-model:visible="dialogVisible"
      :formData="newUser"
      :formFields="formFields"
      :formRules="formRules"
      @confirm="handleConfirm"
    />
    <!-- 用户表格 -->
    <GenericTable :data="filterTableData" :columns="columns" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { FormRules } from "element-plus";
import GenericDialogForm from "@/component/GenericDialogForm.vue";
import GenericTable from "@/component/GenericTable.vue";
import { useRoleStore } from "@/store/roleStore";
import { addUserAPI } from "@/service/login/user";
import cache from "@/utils/cache";
import Swal from "sweetalert2";
import { useUserListStore } from "@/store/userListStore";
import { TableData, RuleForm } from "@/service/login/types";

// 弹窗是否可见
const dialogVisible = ref(false);

// 新用户
const newUser = ref({
  username: "",
  password: "",
  confirmPassword: "",
  role: null,
});

// 表单字段
const formFields = [
  { label: "用户名", prop: "username", type: "input" },
  { label: "密码", prop: "password", type: "input", inputType: "password" },
  {
    label: "确认密码",
    prop: "confirmPassword",
    type: "input",
    inputType: "password",
  },
  {
    label: "角色",
    prop: "role",
    type: "select",
    options: [],
  },
];

// 表单验证规则
const formRules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, message: "用户名长度不能少于3位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
});

// 确认密码
function validateConfirmPassword(rule: any, value: any, callback: any) {
  if (value !== newUser.value.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
}

// 打开添加用户弹窗
async function handleAdd() {
  dialogVisible.value = true;
  const roleStore = useRoleStore();
  await roleStore.getAllRoles();
  const roles = roleStore.roles.value;
  formFields[3].options = roles.map((role: any) => ({
    label: role.name,
    value: role.id,
  }));
}

// 确认添加用户
async function handleConfirm(formData: any) {
  console.log("formData:", formData);
  const { username, password, role } = formData;
  const token = cache.getCache("token");
  const res = await addUserAPI(token, { username, password, roleId: role });
  if (res.data.statusCode === 201) {
    await fetchData();
  } else {
    Swal.fire({
      title: "添加用户失败",
      icon: "error",
    });
  }
}

// 获取用户列表
async function fetchData() {
  await userListStore.getAllUsers();
  tableData.value = userListStore.usersList.value;
  tableData.value.map((user: any) => {
    user.role = user.role.name;
  });
}
// 获取用户列表store
const userListStore = useUserListStore();
onMounted(async () => {
  await fetchData();
});

// 获取用户表格数据
const tableData = ref<TableData[]>([]);
const search = ref("");
const filterTableData = computed(() => {
  return tableData.value.filter((user: TableData) =>
    user.username.includes(search.value)
  );
});
// 获取用户表格列
const columns = [
  { prop: "id", label: "ID", width: 180 },
  { prop: "username", label: "用户名", width: 180 },
  { prop: "role", label: "角色" },
  { prop: "createdAt", label: "创建时间" },
];
</script>
